﻿using System.Data;

using NHibernate;

namespace ZQNB.Common.Data
{
    public class NhUnitOfWork : IUnitOfWork
    {
        private ISession session;
        private ITransaction transaction;

        public NhUnitOfWork(ISession session)
        {
            this.session = session;
        }
        
        public bool IsActive 
        {
            get
            {
                if (this.transaction == null)
                {
                    return false;
                }
                return this.transaction.IsActive;
            }
        }
        public bool WasCommitted
        {
            get
            {
                if (this.transaction == null)
                {
                    return false;
                }
                return this.transaction.WasCommitted;
            }
        }
        public bool WasRolledBack
        {
            get
            {
                if (this.transaction == null)
                {
                    return false;
                }
                return this.transaction.WasRolledBack;
            }
        }

        public void Begin()
        {
            if (this.transaction == null || !this.transaction.IsActive)
            {
                if (this.transaction != null)
                {
                    this.transaction.Dispose();
                }

                this.transaction = this.session.BeginTransaction();
            }
        }

        public void Begin(IsolationLevel isolationLevel)
        {
            if (this.transaction == null || !this.transaction.IsActive)
            {
                if (this.transaction != null)
                {
                    this.transaction.Dispose();
                }

                this.transaction = this.session.BeginTransaction(isolationLevel);
            }
        }

        public void Commit()
        {
            try
            {
                this.transaction.Commit();
            }
            catch
            {
                this.transaction.Rollback();
                throw;
            }
        }

        public void Rollback()
        {
            this.transaction.Rollback();
        }

        public void Dispose()
        {
            if (this.transaction != null)
            {
                this.transaction.Dispose();
                this.transaction = null;
            }

            if (this.session != null)
            {
                this.session.Close();
                this.session.Dispose();
                session = null;
            }
        }
    }
}